<?php
require 'vendor/autoload.php';
include_once "NotORM.php";

$dsn ="mysql:dbname=qqgoto;host=localhost";
$username ="root";
$password = "root";
$pdo = new PDO($dsn,$username,$password);
$pdo->query('SET NAMES UTF-8'); // 设置数据库编码
$db = new NotORM($pdo);
$db->exec("SET NAMES 'utf8'"); 
 
#-------------------------------
$config['displayErrorDetails'] = true;

$config['db']['host']   = "localhost";
$config['db']['user']   = "root";
$config['db']['pass']   = "root";
$config['db']['dbname'] = "qqgoto";

$app = new Slim\App(["settings" => $config]);

spl_autoload_register(function ($classname) {
    require ("../classes/" . $classname . ".php");
});
$container = $app->getContainer();
$container['logger'] = function($c) {
    $logger = new \Monolog\Logger('my_logger');
    $file_handler = new \Monolog\Handler\StreamHandler("../logs/app.log");
    $logger->pushHandler($file_handler);
    return $logger;
};

 
$container['db'] = function ($c) {
    $db = $c['settings']['db'];
    $pdo = new PDO("mysql:host=" . $db['host'] . ";dbname=" . $db['dbname'],
        $db['user'], $db['pass']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
    return $pdo;
};

 
 
$app->get('/', function ($request, $response, $args) {
    $response->write("Welcome to qqgoto!");
    return $response;
});
 
// 获取指定user
$app->get('/user[/{id}]', function ($request, $response, $args) {
	$user = new StdClass();
	$user->id = $args['id'];
	$user->name = "张三feng";
	$user->gender = "male";
	$user->avatar ="http://f.hiphotos.baidu.com/news/crop%3D0%2C0%2C1031%2C619%3Bw%3D638/sign=67bf5edd4d90f60310ffc60704229f2b/50da81cb39dbb6fdbf5b37ca0e24ab18962b37de.jpg";
  
	$newResponse = $response->withHeader('Content-type', 'application/json')->withJson($user);
	return $newResponse;
});

// 获取所有user
$app->get('/users', function ($request, $response, $args) use($db){
	#$arr = selectUsers();
	$arr = $db->user();
	
	
	$newResponse = $response->withJson($arr);
 
	return $newResponse;
});

function selectUsers(){
	$mysql_server_name="localhost"; //数据库服务器名称
    $mysql_username="root"; // 连接数据库用户名
    $mysql_password="root"; // 连接数据库密码
    $mysql_database="qqgoto"; // 数据库的名字
    
	$arr = array();
	
    // 连接到数据库
    $conn= mysqli_connect($mysql_server_name, $mysql_username,$mysql_password,$mysql_database);

    $strsql="select * from users";
    // 执行sql查询
    $result=mysqli_query($conn,$strsql);		
    // 定位到第一条记录
    mysqli_data_seek($result, 0);
    // 循环取出记录

    while ($row=mysqli_fetch_row($result)){
		$user = new StdClass();
		$user->id = $row[0];
		$user->name = $row[1];
		$user->gender = $row[2];
		$user->avatar = $row[3];

		array_push($arr,$user);
    }		

	// 释放资源
    mysqli_free_result($result);
    // 关闭连接
    mysqli_close($conn);  	
	
	return $arr;
}

$app->run();
